package com.ruoyi.system.service;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatLoginService {

    private static final Logger logger = LoggerFactory.getLogger(WechatLoginService.class);

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    private final RestTemplate restTemplate = new RestTemplate();

    public Map<String, Object> getSessionInfo(String code) {
        logger.info("开始获取微信会话信息，appid: {}, code: {}", appid, code);

        // 构建完整的URL
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appid, secret, code);

        logger.info("请求微信接口，URL: {}", url);

        try {
            String response = restTemplate.getForObject(url, String.class);
            logger.info("微信接口返回: {}", response);
            System.out.println(response);
            return JSONObject.parseObject(response);
        } catch (Exception e) {
            logger.error("调用微信接口异常", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("errcode", -1);
            errorResult.put("errmsg", "调用微信接口异常：" + e.getMessage());
            return errorResult;
        }
    }
}
